
package com.weiyuwqj.server.service.invest.module;

import com.weiyuwqj.api.common.Calculator;
import com.weiyuwqj.api.constant.ItemStatus;
import com.weiyuwqj.api.constant.OperateContants;
//import com.weiyuwqj.api.exception.HfException;
//import com.weiyuwqj.api.hengfeng.model.base.HfBaseResponseBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfDataBean;
//import com.weiyuwqj.api.hengfeng.model.base.HfResultBean;
//import com.weiyuwqj.api.hengfeng.model.platform.HfFundFreezeOrTraw;
import com.weiyuwqj.api.model.BasItem;
import com.weiyuwqj.api.model.BusAssetInvest;
import com.weiyuwqj.api.model.BusAssetPackageInvest;
import com.weiyuwqj.api.model.BusAssetPackagePlan;
import com.weiyuwqj.api.model.BusItemAuto;
import com.weiyuwqj.api.model.BusItemInvest;
import com.weiyuwqj.api.model.BusUserStat;
import com.weiyuwqj.api.model.BusVerifyLog;
import com.weiyuwqj.api.util.AutoUtils;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.MyAssertUtils;
import com.weiyuwqj.api.util.RandomCodesUtils;
import com.weiyuwqj.api.util.StringUtils;
import com.weiyuwqj.server.mapper.BasItemMapper;
import com.weiyuwqj.server.mapper.BasUserMapper;
import com.weiyuwqj.server.mapper.BusAssetInvestMapper;
import com.weiyuwqj.server.mapper.BusAssetPackageInvestMapper;
import com.weiyuwqj.server.mapper.BusAssetPackagePlanMapper;
import com.weiyuwqj.server.mapper.BusItemAutoMapper;
import com.weiyuwqj.server.mapper.BusItemAutoSortMapper;
import com.weiyuwqj.server.mapper.BusItemInvestMapper;
import com.weiyuwqj.server.mapper.BusUserStatMapper;
import com.weiyuwqj.server.mapper.BusVerifyLogMapper;
//import com.weiyuwqj.server.pay.PlatformApi;
import com.weiyuwqj.server.service.account.module.DealAction;
import com.weiyuwqj.server.service.account.module.DealModule;
import com.weiyuwqj.server.service.account.module.action.user.invest.InvestDealAction;
import com.weiyuwqj.server.service.finance.module.OperateModule;
import com.weiyuwqj.server.service.finance.module.action.ExpendOperateAction;
import com.weiyuwqj.server.service.finance.module.action.OperateAction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Copyright 2015-2019 Yunfucloud technology co., Ltd.
 * Created by fuxx on 16/2/29.
 */
@Component
public class AutoInvestModule {

    private static Logger log = Logger.getLogger("AutoInvestModule");
    @Autowired
    private BasItemMapper itemMapper;
    @Autowired
    private BasUserMapper userMapper;
    @Autowired
    private BusItemInvestMapper investMapper;
    @Autowired
    private BusVerifyLogMapper verifyLogMapper;
    @Autowired
    private DealModule dealModule;
    @Autowired
    private BusUserStatMapper userStatMapper;
    @Autowired
    private BusAssetPackagePlanMapper assetPackagePlanMapper;
    @Autowired
    private BusAssetInvestMapper assetInvestMapper;
    @Autowired
    private BusAssetPackageInvestMapper packageInvestMapper;
    @Autowired
    private BusItemAutoMapper autoMapper;
    @Autowired
    private BusItemAutoSortMapper autoSortMapper;
    @Autowired
    private OperateModule operateModule;

//    @Autowired
//    private PlatformApi platformApi;

    /**
     * 投标
     * @param userId        用户ID
     * @param amount        投资金额
     * @param item          投资标的
     * @param investType
     * @param freeOrder
     */
    public Map itemDoInvest(Integer userId,BigDecimal amount,BasItem item,Integer investType,
                        String freeOrder,BusItemAuto auto){
        log.info("_________userId_________"+userId+"________investAmount_________:" + amount );
        int itemId=item.getId();
        BusItemInvest invest=new BusItemInvest();
        String investOrder= RandomCodesUtils.getOrderNo();
        Map map=new HashMap();
        map.put("userId", userId);
        BusUserStat stat=userStatMapper.getOneByUserId(map);
        if(stat.getInvestCount()!=0){
            invest.setInvestOrder(investOrder);
        }else {
            invest.setInvestOrder(investOrder+"s");
        }
        BigDecimal scale =item.getItemOngoingAccount().add(amount).multiply(BigDecimal.valueOf(100))
                .divide(item.getItemAccount(), 2, BigDecimal.ROUND_DOWN);
        if((item.getItemOngoingAccount().add(amount)).compareTo(item.getItemAccount())==0){
            scale = new BigDecimal(100);
            itemMapper.updateItemStatus(item.getItemStatus(), ItemStatus.FULL_COMPLETE,itemId);
            fullVerifyLog(item);
        }
        int count = itemMapper.updateItemScale(amount,item.getItemOngoingAccount(),scale,itemId);
        MyAssertUtils.isTrue(count == 1, "item.invest.busy");
        insertBusItemInvest(invest,amount,item,userId,investType,freeOrder,auto.getId());

        DealAction action=new InvestDealAction();
        action.deal(invest.getUserId(),amount,item.getItemName()+"投资冻结");
        count = dealModule.dealAction(action);
        MyAssertUtils.isTrue(count ==1,"item.invest.busy");
        //插入资金明细
        OperateAction operate = new ExpendOperateAction();
        operate.operateAction(investOrder, OperateContants.INVESTORS_INVEST,itemId,
                item.getItemName(),amount);
        operateModule.operateAction(operate);

        map.clear();
        map.put("userId",userId);
        map.put("investAmount",amount);
        userStatMapper.updateInvest(map);
        //规则更新
        map.clear();
        map.put("nowDate",new Date());
        map.put("autoId",auto.getId());
        map.put("userId",userId);
        autoMapper.updateAutoRule(map);
        //排序更新
        map.clear();
        map.put("nowDate",new Date().getTime());
        map.put("autoId",auto.getId());
        map.put("userId",userId);
        autoSortMapper.updateAutoSort(map);

        map.clear();
        map.put("investOrder",investOrder);
        map.put("dealAmount",amount);
        map.put("freezeOrderNo",freeOrder);
        map.put("scale",scale);
        return map;
    }

//    public Map planDoInvest(BusItemAuto auto,BusAssetPackagePlan plan,BigDecimal amount,Integer userId,Integer investType){
//        log.info("_________userId_________"+userId+"________investAmount_________:" + amount );
//        BigDecimal totalAmount = plan.getAmount();
//        BigDecimal onGoingAmount = plan.getOngoingAccount() == null ? BigDecimal.ZERO : plan.getOngoingAccount();
//        //更新项目状态
//        BigDecimal newOnGoingAmount = onGoingAmount.add(amount);
//        BigDecimal scale ;
//        if (newOnGoingAmount.compareTo(totalAmount) < 0) {
//            scale = newOnGoingAmount.multiply(BigDecimal.valueOf(100))
//                    .divide(totalAmount, 2, BigDecimal.ROUND_DOWN);
//        } else {
//            scale = new BigDecimal(100);
//            assetPackagePlanMapper.updatePackagePlanStatus(2, 3, plan.getId());
//            Map map = new HashMap();
//            map.put("fullTime", new Date());
//            map.put("planId", plan.getId());
//            assetPackagePlanMapper.updateFullTime(map);
//        }
//        //更新资产包计划表进度和金额
//        int count = assetPackagePlanMapper.updateAmountAndScale(amount, onGoingAmount, scale, plan.getId());
//        MyAssertUtils.isTrue(count ==1,"item.invest.busy");
//        //插入包投资记录
//        BusAssetPackageInvest packageInvest = new BusAssetPackageInvest();
//        packageInvest.setPackagePlanId(plan.getId());
//        packageInvest.setUserId(userId);
//        packageInvest.setInvestType(investType);
//        packageInvest.setInvestAmount(amount);
//        packageInvest.setAddip(IpUtils.get());
//        packageInvest.setAddtime(new Date());
//        packageInvest.setStatus(2);
//        BasItem basItem = new BasItem();
//        basItem.setItemCycle(plan.getCycle());
//        basItem.setItemRate(plan.getRate());
//        basItem.setItemAddRate(BigDecimal.ZERO);
//        BigDecimal interest = Calculator.addRateInterest(amount, basItem);
//        packageInvest.setInterest(interest);
//
//        packageInvestMapper.insertPackageInvest(packageInvest);
//
//        //操作用户金额
//        String remark = plan.getPackagePlanName() + "投资冻结" + amount + "元";
//        DealAction action = new InvestDealAction();
//        action.deal(userId, amount, remark);
//        count = dealModule.dealAction(action);
//        MyAssertUtils.isTrue(count ==1,"item.invest.busy");
//
//        //统计投资
//        Map map = new HashMap();
//        map.put("userId", userId);
//        map.put("investAmount", amount);
//        userStatMapper.updateInvest(map);
//
//        //规则更新
//        map.clear();
//        map.put("nowDate",new Date());
//        map.put("autoId",auto.getId());
//        map.put("userId",userId);
//        autoMapper.updateAutoRule(map);
//
//        //排序更新
//        map.clear();
//        map.put("nowDate",new Date().getTime());
//        map.put("autoId",auto.getId());
//        map.put("userId",userId);
//        autoSortMapper.updateAutoSort(map);
//
//        String freezeOrderNo ;
//        //第一期生成资产投资记录
//        if (plan.getPeriods() == 1) {
//            List<BasItem> itemList = itemMapper.listUnderByPackageId(plan.getAssetPackageId());
//            BigDecimal remainInvestAmount = amount;
//            for (BasItem item : itemList) {
//                //剩余投资金额小于等于0
//                if (remainInvestAmount.compareTo(BigDecimal.ZERO) <= 0 ) break;
//                BigDecimal itemScale;
//                BigDecimal itemInvestAmount;
//                BigDecimal itemRemainAmount = item.getItemAccount().subtract(item.getItemOngoingAccount());
//                //项目可投金额小于等于0
//                if (itemRemainAmount.compareTo(BigDecimal.ZERO) <= 0 ) continue;
//                if (remainInvestAmount.compareTo(itemRemainAmount) >= 0) {
//                    //投资金额大于标的剩余金额
//                    remainInvestAmount = remainInvestAmount.subtract(itemRemainAmount);
//                    itemInvestAmount = itemRemainAmount;
//                    //更新项目状态
//                    count = itemMapper.updateItemStatus(ItemStatus.OPEN, ItemStatus.FULL_COMPLETE, item.getId());
//                    MyAssertUtils.isTrue(count==1,"debt.invest.busy");
//                    itemScale = new BigDecimal(100);
//                    fullVerifyLog(item);
//                } else {
//                    //投资金额小于标的剩余金额
//                    itemInvestAmount = remainInvestAmount;
//                    remainInvestAmount = BigDecimal.ZERO;
//                    itemScale = (itemInvestAmount.add(item.getItemOngoingAccount())).
//                            multiply(new BigDecimal(100)).
//                            divide(item.getItemAccount(), 2, BigDecimal.ROUND_DOWN);
//                }
//                //更新标的金额和进度
//                count = itemMapper.updateItemScale(itemInvestAmount, item.getItemOngoingAccount(), itemScale, item.getId());
//                MyAssertUtils.isTrue(count==1,"debt.invest.busy");
//                String investOrder=RandomCodesUtils.getOrderNo();
//                insertAssetInvest(userId, item, investType, itemInvestAmount,plan,auto.getId(),investOrder);
//                freezeOrderNo = doFundFreeze(itemInvestAmount,userId);
//                assetInvestMapper.modifyAssetInvestFreezeOrderNo(freezeOrderNo, investOrder);
//            }
//        }else{
//            freezeOrderNo = doFundFreeze(amount,userId);
//            packageInvestMapper.modifyPackageInvestFreezeOrderNoById(freezeOrderNo, packageInvest.getId());
//        }
//        map.clear();
//        map.put("scale",scale);
//        return map;
//    }

//    /**
//     * 投资
//     */
//    public String doFundFreeze(BigDecimal amount,Integer userId){
//        HfFundFreezeOrTraw freezeOrTraw = new HfFundFreezeOrTraw();
//        freezeOrTraw.setAmount(amount.toString());
//        freezeOrTraw.setFreeze_flg("01");
//        freezeOrTraw.setPlatcust(userMapper.selectByPrimaryKey(userId).getPlatformId());
//        freezeOrTraw.setRemark(userId+"投资冻结");
//        freezeOrTraw.setOrder_no(StringUtils.getOrderNo());
//        HfResultBean<HfDataBean> resultBean = platformApi.doFundFreeze(freezeOrTraw);
//        //修改冻结流水号
//        String freezeOrderNo="";
//        if (null != resultBean.getData()) {
//            HfDataBean dataBean = resultBean.getData();
//            return dataBean.getQuery_id();
//        }
//        return freezeOrderNo;
//    }

    /**
     * 插入满标日志
     * @param item
     */
    private void fullVerifyLog(BasItem item){
        //插入日志类型3
        BusVerifyLog log=new BusVerifyLog();
        log.setOperateUserId(1);
        log.setContent("项目满标："+item.getItemName());
        log.setAddtime(new Date());
        log.setType((byte)3);
        log.setItemId(item.getId());
        log.setStatus((byte)1);
        log.setAddip(IpUtils.get());
        verifyLogMapper.insert(log);
    }

    /**
     * 插入包投资表
     * @param userId
     * @param item
     * @param investType
     * @param itemInvestAmount
     * @param plan
     * @param autoId
     */
    private void insertAssetInvest(Integer userId,BasItem item,Integer investType,BigDecimal itemInvestAmount
            ,BusAssetPackagePlan plan,Integer autoId,String investOrder){
        //插入投资记录
        BusAssetInvest assetInvest = new BusAssetInvest();
        assetInvest.setUserId(userId);
        assetInvest.setItemId(item.getId());
        assetInvest.setParentId(0);
        assetInvest.setInvestType(investType);
        assetInvest.setInvestCurrent(1);
        assetInvest.setInvestOrder(investOrder);
        assetInvest.setInvestStatus(0);
        assetInvest.setPackagePlanId(plan.getId());
        assetInvest.setDebtTransferStatus(0);
        assetInvest.setInvestAmount(itemInvestAmount);
        assetInvest.setInvestDealAmount(itemInvestAmount);
        //计算收益利率
        BigDecimal earnRate = AutoUtils.getEarnRate(plan.getCycleUnit(), plan.getCycle(), plan.getRate());
        BigDecimal earnAmount = itemInvestAmount.multiply(earnRate).
                divide(new BigDecimal(100), 2, BigDecimal.ROUND_DOWN);
        assetInvest.setCollectAmount(itemInvestAmount.add(earnAmount));
        assetInvest.setCollectPrincipal(itemInvestAmount);
        assetInvest.setCollectInterest(earnAmount);
        assetInvest.setActualCollectAmount(BigDecimal.ZERO);
        assetInvest.setActualCollectInterest(BigDecimal.ZERO);
        assetInvest.setActualCollectPrincipal(BigDecimal.ZERO);
        assetInvest.setActualUncollectAmount(BigDecimal.ZERO);
        assetInvest.setActualUncollectInterest(BigDecimal.ZERO);
        assetInvest.setActualUncollectPrincipal(BigDecimal.ZERO);
        assetInvest.setAdditionalRateAmount(BigDecimal.ZERO);
        assetInvest.setAddip(IpUtils.get());
        assetInvest.setAddtime(new Date());
        assetInvest.setUpdatetime(new Date());
        assetInvest.setAutoId(autoId);
        assetInvestMapper.insert(assetInvest);
    }

    /**
     * 插入标投资表
     * @param invest
     * @param amount
     * @param item
     * @param userId
     * @param investType
     * @param freeOrder
     * @param autoId
     */
    private void insertBusItemInvest(BusItemInvest invest,BigDecimal amount,BasItem item,Integer userId,
                        Integer investType,String freeOrder,Integer autoId){
        BigDecimal interest= Calculator.getInterest(amount, item);
        invest.setInvestDealAmount(amount);
        BigDecimal totalTicketInterest=BigDecimal.ZERO;
        invest.setCollectInterest(interest);
        invest.setAdditionalRateAmount(totalTicketInterest);
        invest.setUserId(userId);
        invest.setItemId(item.getId());
        invest.setInvestCurrent(0);
        invest.setInvestType(investType);
        invest.setInvestAmount(amount);
        invest.setInvestStatus(0);
        invest.setAddip(IpUtils.get());
        invest.setAddtime(new Date());
        invest.setCollectPrincipal(amount);
        invest.setCollectAmount(amount.add(interest));
        invest.setActualCollectAmount(BigDecimal.ZERO);
        invest.setActualCollectInterest(BigDecimal.ZERO);
        invest.setActualCollectPrincipal(BigDecimal.ZERO);
        invest.setActualUncollectAmount(BigDecimal.ZERO);
        invest.setActualUncollectInterest(BigDecimal.ZERO);
        invest.setActualUncollectPrincipal(BigDecimal.ZERO);
        invest.setDebtTransferStatus(0);
        invest.setFreezeOrderNo(freeOrder);
        invest.setAutoId(autoId);
        investMapper.insertInvest(invest);
    }


}

